package k8s_agent

import (
	"code.gitea.io/gitea/modules/log"
	"code.gitea.io/gitea/modules/setting"
	"context"

	dynamicclient "k8s.io/client-go/dynamic"
	clientgorest "k8s.io/client-go/rest"
	"k8s.io/client-go/tools/clientcmd"
	clientgocmdtools "k8s.io/client-go/tools/clientcmd"
)

// GetKubernetesClient
func GetKubernetesClient(ctx *context.Context) (dynamicclient.Interface, error) {
	// 1.0 尝试从集群外获取 kubectl 配置信息
	config, err := clientcmd.BuildConfigFromFlags("", clientgocmdtools.RecommendedHomeFile)
	if err != nil {
		// 1.1 集群外尝试失败，改从集群内获取 kubectl 配置信息
		log.Warn("Failed to obtain Kubernetes config outside of cluster: " + clientgocmdtools.RecommendedHomeFile)
		config, err = clientgorest.InClusterConfig()
		if err != nil {
			log.Error("Failed to obtain Kubernetes config both inside/outside of cluster, the DevContainer is Disabled")
			setting.Devstar.Devcontainer.Enabled = false
			return nil, err
		}
	}
	// 2. 根据 k8s 配置信息构建 ClientSet
	dynamicClient, err := dynamicclient.NewForConfig(config)
	if err != nil {
		return nil, err
	}
	return dynamicClient, err
}
